<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="步骤名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入步骤名称"
          style="width: 240px"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:step:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:step:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:step:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:step:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stepList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="序号" align="center" width="50" type="index" />
      <el-table-column label="步骤执行顺序" align="center" prop="stepOrder" />
      <el-table-column label="步骤名称" align="center" prop="name" />
      <el-table-column label="数据提取规则 (JSON数组格式)" align="center" prop="extractRules" width="260px" :show-overflow-tooltip="true" />
      <el-table-column label="断言规则 (JSON数组格式)" align="center" prop="assertionRules" width="260px" :show-overflow-tooltip="true" />
      <el-table-column label="失败时是否中断场景" align="center" prop="breakOnFailure">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.breakOnFailure"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:step:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:step:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改测试步骤对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="stepRef" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="步骤执行顺序" prop="stepOrder">
          <el-input v-model="form.stepOrder" placeholder="请输入步骤执行顺序" />
        </el-form-item>
        <el-form-item label="步骤名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入步骤名称" />
        </el-form-item>
        <el-form-item label="步骤接口名称" prop="apiName">
          <el-input v-model="form.apiName" placeholder="选择接口后系统自动填充接口相关信息" disabled readonly >
            <template #append>
              <el-button type="info" icon="Search" @click="chooseApiDefinition"/>
            </template>
          </el-input>
        </el-form-item>
        <!--隐藏的输入框存储接口定义ID-->
        <el-form-item label="引用的接口定义ID" prop="apiId" style="display: none;">
          <el-input v-model="form.apiId" placeholder="请输入引用的接口定义ID" />
        </el-form-item>
        <el-form-item label="数据提取规则 (JSON数组格式)" prop="extractRules">
          <el-input v-model="form.extractRules" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="断言规则 (JSON数组格式)" prop="assertionRules">
          <el-input v-model="form.assertionRules" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="json schema文件" prop="jsonSchemaFile">
          <file-upload v-model="form.jsonSchemaFile"/>
        </el-form-item>
        <el-form-item label="失败时是否中断场景" prop="breakOnFailure">
          <el-radio-group v-model="form.breakOnFailure">
            <el-radio
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="步骤描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入步骤描述" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 选择接口表单-->
    <el-dialog
        title="选择接口"
        v-model="isChooseApiDefinitionDialogVisible"
        width="60%"
    >

      <div class="app-container">
        <!-- 查询表单 -->
        <el-form :model="queryApiDefinitionParams" ref="queryApiDefinitionRef" :inline="true" v-show="showSearch">
          <el-form-item label="接口名称" prop="name">
            <el-input
                v-model="queryApiDefinitionParams.name"
                placeholder="请输入接口名称"
                style="width: 240px"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="接口分类" prop="category">
            <el-select v-model="queryApiDefinitionParams.category"
                       style="width: 240px"
                       placeholder="请选择接口分类" clearable>
              <el-option
                  v-for="dict in api_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="接口地址" prop="url">
            <el-input
                v-model="queryApiDefinitionParams.url"
                placeholder="请输入接口名称"
                style="width: 240px"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleApiDefinitionQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetApiDefinitionQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row>
          <!-- 表格数据展示 -->
          <el-table v-loading="loading" :data="apiDefinitionList"
                    highlight-current-row
                    stripe
                    @current-change="handleCurrentChange">
            <el-table-column label="序号" align="center" width="50" type="index" />
            <el-table-column label="接口名称" align="center" prop="name" />
            <el-table-column label="HTTP方法" align="center" prop="method">
              <template #default="scope">
                <dict-tag :options="http_method" :value="scope.row.method"/>
              </template>
            </el-table-column>
            <el-table-column label="接口分类" align="center" prop="category">
              <template #default="scope">
                <dict-tag :options="api_category" :value="scope.row.category"/>
              </template>
            </el-table-column>
            <el-table-column label="接口地址" align="center" prop="url" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建人" align="center" prop="createBy" />
          </el-table>
          <pagination
              v-show="apiDefinitionTotal>0"
              :total="apiDefinitionTotal"
              v-model:page="queryApiDefinitionParams.pageNum"
              v-model:limit="queryApiDefinitionParams.pageSize"
              @pagination="getApiDefinitionList"
          />
        </el-row>

      </div>

    </el-dialog>

  </div>
</template>

<script setup name="Step">
import { listStep, getStep, delStep, addStep, updateStep } from "@/api/business/step"
import {listApidefinition} from "@/api/business/apidefinition.js";

const { proxy } = getCurrentInstance()
const { sys_yes_no, api_category, http_method } = proxy.useDict('sys_yes_no', 'api_category', 'http_method')

const stepList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
    // 固定场景ID
    scenarioId: proxy.$route.query.scenarioId,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    scenarioId: proxy.$route.query.scenarioId,
    name: null,
  },
  // 接口查询表单
  queryApiDefinitionParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    category: null,
    url: null,
  },
  rules: {
  }
})

const { queryParams, queryApiDefinitionParams, form, rules } = toRefs(data)

/** 查询测试步骤列表 */
function getList() {
  loading.value = true
  listStep(queryParams.value).then(response => {
    stepList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  const currentScenarioId = form.value.scenarioId;  // 保存当前 scenarioId
  form.value = {
    id: null,
    scenarioId: currentScenarioId,
    stepOrder: null,
    name: null,
    apiId: null,
    extractRules: null,
    assertionRules: null,
    jsonSchemaFile: null,
    breakOnFailure: null,
    description: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    delFlag: null
  }
  proxy.resetForm("stepRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加测试步骤"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getStep(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改测试步骤"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["stepRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStep(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addStep(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除测试步骤编号为"' + _ids + '"的数据项？').then(function() {
    return delStep(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/step/export', {
    ...queryParams.value
  }, `step_${new Date().getTime()}.xlsx`)
}

getList()


// 接口选择弹窗
const isChooseApiDefinitionDialogVisible = ref(false);
// 过滤一下再选择可以签合同的商机
const apiDefinitionList = ref([])
// 可选接口总数
const apiDefinitionTotal = ref(0)

// 选择接口按钮
function chooseApiDefinition() {
  resetApiDefinitionQuery()
  // 打开选择弹窗（不需要请求后端，这里只是为了回显）
  isChooseApiDefinitionDialogVisible.value = true;
}
/** 重置按钮操作 */
function resetApiDefinitionQuery() {
  proxy.resetForm("queryApiDefinitionRef");
  handleApiDefinitionQuery();
}
/** 搜索按钮操作 */
function handleApiDefinitionQuery() {
  queryApiDefinitionParams.value.pageNum = 1;
  getApiDefinitionList();
}
// 获取可选接口列表
function getApiDefinitionList() {
  listApidefinition(queryApiDefinitionParams.value).then(response => {
    apiDefinitionList.value = response.rows
    apiDefinitionTotal.value = response.total
  })
}
// 表格选中数据
function handleCurrentChange(currentRow) {
  if (!currentRow) return; // 如果没有选中任何行，直接返回
  proxy.$modal.confirm(`是否确认选中接口${currentRow.name}`)
      .then(() => {
        // 用户确认选择
        form.value.apiId = currentRow.id;
        form.value.apiName = currentRow.name;

        proxy.$modal.msgSuccess("接口选中成功");
        // 关闭选择对话框
        isChooseApiDefinitionDialogVisible.value = false;
      })
      .catch(() => {
        // 用户取消选择
        proxy.$modal.msgWarning("取消选中");
      });
}
</script>
